package com.valuegroup.smarttodo.ui.programme.curriculum;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseRecyclerAdapter;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.vo.AppCustomCfg;
import com.valuegroup.smarttodo.data.vo.CurriculumEventVo;
import com.valuegroup.smarttodo.data.vo.CurriculumItemVo;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.plugins.progressbar.roundcorner.RoundCornerProgressBar;
import com.valuegroup.smarttodo.util.Cfg;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 课程主页
 */
public class CurriculumFragment extends Fragment {

    @BindView(R.id.recycler)
    RecyclerView recyclerView;

    private CurriculumAdapter adapter;
    private Unbinder unbinder;
    private AppCustomCfg cfg;
    private boolean initFinish;

    public static CurriculumFragment newInstance() {
        return new CurriculumFragment();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_curriculum, container, false);
        unbinder = ButterKnife.bind(this, view);
        cfg = Cfg.getCfg(getContext());
        initFinish = true;

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        adapter = new CurriculumAdapter(view.getContext(), loadData(), multiTypeSupport);
        recyclerView.setAdapter(adapter);
        setHasOptionsMenu(true);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        //先clear()一下, 这样按钮就只有Fragment中设置的自己的了, 不会有Activity中的按钮.
        menu.clear();
        inflater.inflate(R.menu.menu_curriculum, menu);
    }

    @Override
    public void onPrepareOptionsMenu(@NonNull Menu menu) {
        menu.findItem(R.id.m2).setTitle(!cfg.isCurriculumHideFinish() ? R.string.curriculum_m2 : R.string.curriculum_m2_o);

        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);

        switch (item.getItemId()) {
            case R.id.m1:
                startActivityForResult(new Intent(getContext(), CurriculumSetActivity.class), 1003);
                break;
            case R.id.m2:
                // 隐藏已完成项
                cfg.setCurriculumHideFinish(!cfg.isCurriculumHideFinish());
                Cfg.saveCfg(getContext(), cfg);

                refreshAllData();
                break;
        }
        return true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        // 会闪暂时屏蔽
        /*if (isVisibleToUser && initFinish) {
            refreshAllData();
        }*/
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        refreshData(data);
    }

    private List<CurriculumItemVo> loadData() {
        return ServiceFactory.getInstance().getCurriculumService().findCurriculumForHome(cfg.isCurriculumHideFinish());
    }

    /**
     * 更新列表中某条数据
     * 没有指定的刷新内容时，刷新整个列表
     *
     * @param intent
     */
    private void refreshData(Intent intent) {
        if (intent == null) {
            refreshAllData();
            return;
        }

        long id = intent.getLongExtra(CurriculumOrderActivity.PARAMS_KEY, 0);
        int position = intent.getIntExtra(CurriculumOrderActivity.PARAMS_POSITION, 0);

        if (id == 0) {
            refreshAllData();
            return;
        }

        // 刷新列表中当前操作记录
        CurriculumItemVo data = ServiceFactory.getInstance().getCurriculumService().getCurriculumItemVo(id);
        adapter.refreshData(position, data);

        // 平移到指定位置
        recyclerView.smoothScrollToPosition(position);
    }

    private void refreshAllData() {
        // 刷新列表数据
        adapter.refreshListData(loadData());
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    class CurriculumAdapter extends BaseRecyclerAdapter<CurriculumItemVo> {

        CurriculumAdapter(Context context, List<CurriculumItemVo> data, MultiTypeSupport multiType) {
            super(context, data, multiType);
        }

        @Override
        public void bindView(BaseViewHolder v, CurriculumItemVo data, int position) {

            v.getView(R.id.layoutRoot).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(view.getContext(), CurriculumOrderActivity.class);
                    intent.putExtra(CurriculumOrderActivity.PARAMS_KEY, data.getId());
                    intent.putExtra(CurriculumOrderActivity.PARAMS_POSITION, position);
                    startActivityForResult(intent, 1001);
                }
            });

            // 进度条
            RoundCornerProgressBar bar = v.getView(R.id.tagProgress);
            bar.setProgress(data.getLabProgress());

            //v.setImageResource(R.id.tagIcon, R.drawable.habit_study);
            v.setViewVisibility(R.id.tagAuto, data.isShowAuto());

            v.setText(R.id.labTitle, data.getLabTitle());
            v.setText(R.id.labPercent, String.format(getResources().getString(R.string.percent_tag), Math.round(data.getLabProgress())));
            v.setText(R.id.labBranch, String.format(getResources().getString(R.string.curriculum_branch_lab), data.getBranchFinish(), data.getBranchTotal()));
            if (data.isShowFinish()) {
                v.setText(R.id.labDate, String.format(getResources().getString(R.string.curriculum_enddate_lab), DateUtils.date2str(data.getLabDate(), DateUtils.F30)));
            } else {
                v.setText(R.id.labDate, String.format(getResources().getString(R.string.curriculum_predate_lab), DateUtils.date2str(data.getLabDate(), DateUtils.F30)));
            }

            v.setViewVisibility(R.id.tagFinish, data.isShowFinish()); // 完成状态
            v.setViewVisibility(R.id.labDate, !data.isShowFinish());// 截止时间

            RequestOptions options = RequestOptions
                    .bitmapTransform(new RoundedCorners(6)) //设置图片圆角角度
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                    .skipMemoryCache(true)//不做内存缓存
                    .placeholder(R.drawable.ic_default_image)//图片加载出来前，显示的图片
                    .fallback(R.drawable.ic_default_image) //url为空的时候,显示的图片
                    .error(R.drawable.ic_default_image);//图片加载失败后，显示的图片

            Uri u = new Uri.Builder().scheme("file").path("//" + data.getImgCover()).build();
            ImageView tagIcon = v.getView(R.id.tagIcon);
            Glide.with(CurriculumFragment.this).load(u)
                    .apply(options)
                    .into(tagIcon);
        }

        private List<CurriculumEventVo> loadChildData(Long id) {
            return ServiceFactory.getInstance().getCurriculumService().findCurriculumEventForHome(id);
        }
    }


    private BaseRecyclerAdapter.MultiTypeSupport multiTypeSupport = new BaseRecyclerAdapter.MultiTypeSupport<CurriculumItemVo>() {
        @Override
        public int getLayoutId(List<CurriculumItemVo> datas, int position) {
            if (position == 0) {
                return R.layout.item_default_header;
            } else if (position == (datas.size() + 1)) {
                return R.layout.item_default_bottom;
            } else {
                return R.layout.item_curriculum;
            }
        }

        @Override
        public int getAppendHeadLayoutSize() {
            return 1;
        }

        @Override
        public int getAppendBottomLayoutSize() {
            return 1;
        }

        @Override
        public boolean isBodyLayout(int dataSize, int position) {
            if (position == 0 || position == (dataSize + 1)) {
                return false;
            } else {
                return true;
            }
        }
    };

}
